package com.yzf.smsforward;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.telephony.SmsMessage;
import android.text.TextUtils;
import android.util.Log;


import com.yzf.smsforward.manager.LoginManager;
import com.yzf.smsforward.utils.HttpXUtils;
import com.yzf.smsforward.utils.Utils;
import com.yzf.smsforward.utils.log.LogcatFileManager;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Date;

import static com.yzf.smsforward.Constants.TAG;

/**
 * 项目名称：FoldingVerifyCode
 * 类描述：通过广播接收短信并处理
 * 创建人：Administrator
 * 创建时间：2019年10月1日
 */
public class SMSReceiver extends BroadcastReceiver {

    //    private int msgLength = -1;
    //    private String yzmMsg = "";
    private Activity mActivity;

    public SMSReceiver() {
    }

    public SMSReceiver(Activity activity) {
        this.mActivity = activity;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction() == null) {
            return;
        }
        if (intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")) {
            Bundle bundle = intent.getExtras();
            Log.e(TAG, "SMSReceiver  onReceive");

            String bcd = "";
            SmsMessage msg;
            if (null != bundle) {
                Object[] smsObj = (Object[]) bundle.get("pdus");
                if (smsObj == null) {
                    return;
                }
                for (Object object : smsObj) {
                    bcd = Utils.bcd2Str((byte[]) object);
                }
                Log.e(TAG, "BCD" + bcd);
                String bcdsp = Utils.getValueFromSP(context, Constants.MSG_PDUS, Constants.HTTPS_URL_KEY);
                if (TextUtils.isEmpty(bcdsp)) {
                    Utils.save2SP(context, Constants.MSG_PDUS, Constants.HTTPS_URL_KEY, bcd);
                } else {
                    if (bcdsp.equals(bcd)) {
                        return;
                    } else {
                        Utils.save2SP(context, Constants.MSG_PDUS, Constants.HTTPS_URL_KEY, bcd);
                    }
                }
                String receiveTime = "";
                String messageBody = "";
                Constants.code = "";
                for (int i = 0; i < smsObj.length; i++) {
                    Log.e(TAG, "==================msg======iiiiii=========== " + i);
                    try {
                        msg = SmsMessage.createFromPdu((byte[]) smsObj[i]);
                        if (msg == null) {
                            Log.e(TAG, "=================i==================");
                        } else {
                            Log.e(TAG, "==================msg================= " + msg.toString());
                        }
                        //                        long mills = msg.getTimestampMillis();
                        long mills = System.currentTimeMillis();

                        Log.e(TAG, "mills" + mills);
                        Date date = new Date(mills);//时间
                        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        receiveTime = format.format(date);
                        if (msg == null) {
                            return;
                        }

                        Log.e(TAG, msg.getOriginatingAddress() + "+++++++++++++++++++++++" + msg.getDisplayMessageBody());
                        Log.e(TAG, msg.getOriginatingAddress() + "+++++++++++++++++++++++" + msg);
                        Log.e(TAG, "msg" + msg);
                        Log.e(TAG, "receiveTime" + receiveTime);
                        Log.e(TAG, "EmailBody" + msg.getEmailBody());
                        Log.e(TAG, "EmailFrom" + msg.getEmailFrom());
                        Log.e(TAG, "OriginatingAddress" + msg.getOriginatingAddress());
                        Log.e(TAG, "DisplayMessageBody" + msg.getDisplayMessageBody());
                        Log.e(TAG, "MessageBody" + msg.getMessageBody());
                        Log.e(TAG, "DisplayOriginatingAddress" + msg.getDisplayOriginatingAddress());
                        Log.e(TAG, "PseudoSubject" + msg.getPseudoSubject());
                        Log.e(TAG, "ServiceCenterAddress" + msg.getServiceCenterAddress());
                        Log.e(TAG, "Status" + msg.getStatus() + "");
                        Log.e(TAG, "StatusOnSim" + msg.getStatusOnSim() + "");
                        Log.e(TAG, "IndexOnSim" + msg.getIndexOnSim() + "");
                        Constants.serverCenter = msg.getServiceCenterAddress();
                        Constants.msgBody = getSMSByText(context, msg.getMessageBody());
                        Constants.sendPhoneNum = msg.getOriginatingAddress();
                        Constants.receviveTime = receiveTime;
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    boolean isContains = false;
                    if (Constants.matching_rules_array.length > 0) {
                        if (!TextUtils.isEmpty(Constants.msgBody)) {
                            for (String s : Constants.matching_rules_array) {
                                Log.e(TAG, "s----------" + s);
                                if (!TextUtils.isEmpty(s) && Constants.msgBody.contains(s)) {
                                    isContains = true;
                                    break;
                                }
                            }
                        } else {
                            LogcatFileManager.showToast(context, "短信内容错误...");
                            return;
                        }
                    } else {
                        LogcatFileManager.showToast(context, "无匹配规则，不上报...");
                        return;
                    }
                    if (!isContains) {
                        return;
                    }
                    final String phoneNum;
                    if (Constants.isDulCard) {
                        if (Constants.isSan) {
                            Log.e(TAG, "getPhoneNOByTextBySamsung==" + Constants.msgBody);
                            phoneNum = getPhoneNOByTextBySamsung(context, Constants.msgBody);
                        } else {
                            Log.e(TAG, "Constants. ==" + Constants.msgBody);
                            phoneNum = getPhoneNoByText(context, Constants.msgBody);
                        }
                    } else {
                        phoneNum = Constants.numbers.get(Constants.TEL1_KEY);
                    }

                    if (mActivity != null && TextUtils.isEmpty(phoneNum)) {
                        mActivity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                TelDialog telDialog = new TelDialog(mActivity);
                                if (!telDialog.isShowing()) {
                                    telDialog.show();
                                }
                            }
                        });
                    }

                    Constants.phoneNum = phoneNum;
                    Log.e(TAG, "-------------phoneNum--------------- " + phoneNum);
                    Log.e(TAG, "messageBody==" + Constants.msgBody);
                    Log.e(TAG, "-------------receiveTime--------------- " + receiveTime);
                    Log.e(TAG, "-------------Constants.sendPhoneNum--------------- " + Constants.sendPhoneNum);
                    if (!TextUtils.isEmpty(phoneNum) && !TextUtils.isEmpty(Constants.msgBody)) {
                        loopSaveMsg(context, Constants.msgBody, phoneNum, Constants.sendPhoneNum, receiveTime);
                        return;
                    }
                }
            }
        }
    }

    private synchronized void loopSaveMsg(final Context context, String msg, final String phoneNum, final String smsNum,
                                          final String receiveTime) {
        LoginManager.getInstance().saveMsg1(context, msg, phoneNum, smsNum, receiveTime, new HttpXUtils.MyCallback() {
            @Override
            public void myResult(String str) {
                Message message = Message.obtain();
                Sms sms = new Sms();
                Log.e(TAG, "saveMsg onSuccess==" + str);
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(str);
                    final String code = jsonObject.getString("code");
                    if (code.equals("100000")) {
                        String strJson = jsonObject.getString("data");
                        jsonObject = new JSONObject(strJson);
                        Log.e(TAG, "setReceiveTime==" + jsonObject.getString("saveTime"));
                        sms.setReceiveTime(jsonObject.getString("saveTime"));
                        sms.setIsSave(jsonObject.getString("isSave"));
                        sms.setIsSuccess("true");
                        sms.setErrorCode(code);
                    } else {
                        sms.setIsSuccess("false" + "\n错误码: " + code);
                        sms.setErrorCode(code);
                        sms.setReceiveTime(Constants.receviveTime);
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
                sms.setBody(Constants.msgBody);
                sms.setOriginatingAddress(smsNum);
                sms.setReceverPhoneNo(phoneNum);
                sms.setServiceCenterAddress(Constants.serverCenter);
                message.obj = sms;
                if (CardAdapter.smsHandler != null) {
                    Log.e(TAG, "smsHandler msg");
                    CardAdapter.smsHandler.handleMessage(message);
                }
            }
        });
    }

    private String getPhoneNoByText(Context context, String key) {
        try {
            Thread.sleep(4000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Log.e(TAG, "getPhoneNoByText key = " + key);
        //访问内容提供者获取短信
        ContentResolver cr = context.getContentResolver();
        //短信内容提供者的主机名
        Cursor cursor = cr.query(Uri.parse("content://sms"), new String[]{"address", "date", "body",
                        "type", "_id", "thread_id", "person", "date_sent", "protocol", "read",
                        "status", "sub_id", "seen", "service_center"},
                null, null, null);
        if (cursor == null) {
            return "";
        }
        while (cursor.moveToNext()) {
            String body = cursor.getString(2);
            int sub_id = cursor.getInt(11);

            //            if(sub_id == -1){
            //                return "-1";
            //            }
            //            Log.e(TAG, "msgLength = " + msgLength);
            Log.e(TAG, "body.length() = " + body.length());
            //            if (body.length() > msgLength) {
            //                body = body.substring(0, msgLength);
            //            }
            Log.e(TAG, "getPhoneNoByText body = " + body);
            if (body.contains(key)) {
                return Utils.getPhoneNoBySubId(context, String.valueOf(sub_id));
            }
        }
        cursor.close();
        return "";
    }

    private String getSMSByText(Context context, String key) {
        try {
            Thread.sleep(4000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Log.e(TAG, "getSMSByText key = " + key);
        //访问内容提供者获取短信
        ContentResolver cr = context.getContentResolver();
        //短信内容提供者的主机名
        Cursor cursor = cr.query(Uri.parse("content://sms"), new String[]{"address", "date", "body",
                        "type", "_id", "thread_id", "person", "date_sent", "protocol", "read",
                        "status", "sub_id", "seen", "service_center"},
                null, null, null);
        if (cursor == null) {
            return "";
        }
        while (cursor.moveToNext()) {
            String address = cursor.getString(0);
            long date = cursor.getLong(1);
            String body = cursor.getString(2);
            int type = cursor.getInt(3);
            int _id = cursor.getInt(4);
            int thread_id = cursor.getInt(5);
            int person = cursor.getInt(6);
            int date_sent = cursor.getInt(7);
            int protocol = cursor.getInt(8);
            int read = cursor.getInt(9);
            int status = cursor.getInt(10);
            int sub_id = cursor.getInt(11);
            int seen = cursor.getInt(12);
            String serviceCenter = cursor.getString(13);

            Log.d(TAG, "address = " + address);
            Log.e(TAG, "date = " + date);
            Log.e(TAG, "body = " + body);
            Log.d(TAG, "type = " + type);
            Log.d(TAG, "_id = " + _id);
            Log.d(TAG, "thread_id = " + thread_id);
            Log.d(TAG, "person = " + person);
            Log.d(TAG, "date_sent = " + date_sent);
            Log.d(TAG, "protocol = " + protocol);
            Log.d(TAG, "read = " + read);
            Log.d(TAG, "status = " + status);
            Log.d(TAG, "sub_id = " + sub_id);
            Log.d(TAG, "seen = " + seen);
            Log.d(TAG, "serviceCenter = " + serviceCenter);

            //            if(sub_id == -1){
            //                return "-1";
            //            }
            //            Log.e(TAG, "msgLength = " + msgLength);
            Log.e(TAG, "body.length() = " + body.length());
            //            if (body.length() > msgLength) {
            //                body = body.substring(0, msgLength);
            //            }
            Log.e(TAG, "getSMSByText body = " + body);
            if (!TextUtils.isEmpty(body)) {
                return body;
            }
        }
        cursor.close();
        return "";
    }


    private String getPhoneNOByTextBySamsung(Context context, String msg) {
//        try {
//            Thread.sleep(4000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        Uri uri = Uri.parse("content://sms/inbox");
        ContentResolver cr = context.getContentResolver();
        //                        短信内容提供者的主机名
        Cursor cur = cr.query(uri, null,
                null, null, null);
        String msgBody;
        Log.e(TAG, "getPhoneNOByTextBySamsung msg = " + msg);
        try {
            JSONObject json = new JSONObject();
            int msgLength = msg.length();
            if (cur == null) {
                return "";
            }
            while (cur.moveToNext()) {
                int length = cur.getColumnCount();
                for (int i = 0; i < length; i++) {
                    json.put(cur.getColumnName(i), cur.getString(i));
                }
                Log.e(TAG, "getPhoneNOByTextBySamsung json = " + json.toString());

                msgBody = json.getString("body");
                if (msgBody.length() > msgLength) {
                    msgBody = msgBody.substring(0, msgLength);
                }
                if (msgBody.equals(msg)) {
                    String simSlot = json.getString("sim_slot");
                    if (simSlot.equals("1")) {
                        return Constants.numbers.get(Constants.TEL2_KEY);
                    } else {
                        return Constants.numbers.get(Constants.TEL1_KEY);
                    }
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        cur.close();
        return "";
    }
}
